#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <termios.h>
#include <stdio.h>
#include <unistd.h>

#include "uart.h"

const int rxbuf_size =512;

void ConfigOBDPort(int fd){

    struct termios attr;

    //get the current options
    tcgetattr(fd,&attr);

    //set the baud rates to 38400
    cfsetispeed(&attr,B9600);
    cfsetospeed(&attr,B9600);

    //setting parity checking as 8N1
    attr.c_cflag &= ~PARENB;
    attr.c_cflag &= ~CSTOPB;
    attr.c_cflag &= ~CSIZE;
    attr.c_cflag |= CS8;
    attr.c_cflag &= ~CRTSCTS;

    //enable teh receiver and set local mode
    attr.c_cflag |= (CLOCAL | CREAD);

    //Set the new options
    tcsetattr(fd,TCSANOW,&attr);

    printf("Set Port Finish!\n");
}

int ReadData(int fd,char *rxbuf){

    char *bufptr;
    int nread=0;
    int rxnum=0;
    unsigned long timeout=LONG_TIMEOUT;

    bufptr = rxbuf;

    while(timeout--){

        nread = read(fd,bufptr,rxbuf_size+rxbuf-bufptr-1);

        if(nread>0)
            bufptr+=nread;

        if(bufptr[-1]==0x3e)
            break;
    }

    if(timeout<0){

        printf("Read from OBD Timeout!!!\n");
        return -1;
    }
    else{

        rxnum = bufptr - rxbuf;
    }
	tcflush(fd, TCIOFLUSH);
    return rxnum;

}

